package com.wms.controller;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wms.annotation.MyLog;
import com.wms.entity.StoreReturn;
import com.wms.entity.StoreReturnDTO;
import com.wms.listener.StoreReturnListener;
import com.wms.service.StoreReturnService;
import com.wms.util.DateUtils;
import com.wms.util.R;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author TianWenHe
 * @date 2025/4/27
 * @desc 退货入库
 */
@RestController
@RequestMapping("/store/return")
public class StoreReturnController {
    private Logger logger = LogManager.getLogger(StoreReturnController.class);

    @Autowired
    private StoreReturnService storeReturnService;

    /**
     * 分页查询退货入库记录
     */
    @GetMapping("/find")
    @MyLog(value = "分页查询退货入库记录", type = "查询")
    public R find(StoreReturnDTO storeReturnDTO) {
        logger.info("分页查询退货入库记录");
        PageHelper.startPage(storeReturnDTO.getPageNum(), storeReturnDTO.getPageSize());
        List<StoreReturn> storeReturns = storeReturnService.find(storeReturnDTO);
        return R.ok(new PageInfo<>(storeReturns));
    }

    /**
     * 新增退货入库记录
     */
    @PostMapping("/add")
    @MyLog(value = "新增退货入库记录", type = "新增")
    public R add(@RequestBody StoreReturn storeReturn) {
        logger.info("新增退货入库记录");
        Long id = storeReturnService.add(storeReturn);
        return R.ok(id);
    }

    /**
     * 修改退货入库记录
     */
    @PutMapping("/update")
    @MyLog(value = "修改退货入库记录", type = "修改")
    public R update(@RequestBody StoreReturn storeReturn) {
        logger.info("修改退货入库记录");
        storeReturnService.update(storeReturn);
        return R.ok();
    }

    /**
     * 批量删除退货入库记录
     */
    @DeleteMapping("/delete")
    @MyLog(value = "批量删除退货入库记录", type = "删除")
    public R delete(@RequestParam List<Long> ids){
        logger.info("批量删除退货入库记录");
        storeReturnService.delete(ids);
        return R.ok();
    }

    /**
     * 批量导入退货入库记录
     */
    @PostMapping("/import")
    @MyLog(value = "批量导入退货入库记录", type = "导入")
    public R importExcel(MultipartFile file) throws IOException {
        logger.info("批量导入退货入库记录");
        EasyExcel.read(file.getInputStream(), StoreReturn.class, new StoreReturnListener(storeReturnService)).sheet().doRead();
        return R.ok();
    }

    /**
     * 导出退货入库记录
     */
    @GetMapping("/export")
    @MyLog(value = "导出退货入库记录", type = "导出")
    public void export(HttpServletResponse response) throws IOException {
        logger.info("导出退货入库记录");

        // 查询全部退货入库记录
        List<StoreReturn> storeReturns = storeReturnService.find(new StoreReturnDTO());

        // 所有不为空的时间减8小时，这样Excel表中的时间才与数据库时间一致
        for (StoreReturn storeReturn : storeReturns) {
            if (storeReturn.getCreateTime() != null) {
                storeReturn.setCreateTime(DateUtils.subtractFixedEightHours(storeReturn.getCreateTime()));
            }
            if(storeReturn.getSortingTime() != null){
                storeReturn.setSortingTime(DateUtils.subtractFixedEightHours(storeReturn.getSortingTime()));
            }
            if(storeReturn.getStorageTime() != null){
                storeReturn.setStorageTime(DateUtils.subtractFixedEightHours(storeReturn.getStorageTime()));
            }
        }

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("退货入库记录", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        // 写入 Excel 并下载
        EasyExcel.write(response.getOutputStream(), StoreReturn.class)
                .autoCloseStream(Boolean.FALSE)
                .sheet("退货入库记录")
                .doWrite(storeReturns);
    }

}
